// 修改图片地址为oss地址
export const getOssUrl = (url) => {
  if (url.startsWith('http://api.xiaozhucaishui.com'))
    return url.replace('http://api.xiaozhucaishui.com', 'https://xzcs-video.oss-cn-beijing.aliyuncs.com')
  else if (url.startsWith('https://api.xiaozhucaishui.co'))
    return url.replace('https://api.xiaozhucaishui.com', 'https://xzcs-video.oss-cn-beijing.aliyuncs.com')

  else if (url.startsWith('http://dev.xiaozhucaishui.co'))
    return url.replace('http://dev.xiaozhucaishui.com', 'https://xzcs-video.oss-cn-beijing.aliyuncs.com')
  else if (url.startsWith('https://dev.xiaozhucaishui.co'))
    return url.replace('https://dev.xiaozhucaishui.com', 'https://xzcs-video.oss-cn-beijing.aliyuncs.com')

  else if (url.startsWith('http://resources.xiaozhucaishui.com'))
    return url.replace('http://resources.xiaozhucaishui.com', 'https://xzcs-video.oss-cn-beijing.aliyuncs.com')

  return url

};

// 参数is=true 直接调用不判断当前滚动位置
export const goTop = (top, is = false) => {
  try {
    let res = document.body.scrollTop || document.documentElement.scrollTop;
    if (res >= 300 || is) { //当大于400px，按钮出现
      document.body.scrollTop = top ? top : 0;
      document.documentElement.scrollTop = top ? top : 0;
    }
  } catch (error) {

  }

}

export const goTopSmooth = (top, is = false) => {
  try {
    document.querySelector("#topNav").scrollIntoView({
      block: "start",
      behavior: "smooth",
    });
  } catch (error) {

  }

}


export const showMessage = function (first_answer) {
  if (first_answer && first_answer.length > 0) {
    let messages = "";
    for (let item of first_answer) {
      let msg = ''
      if (item.message)
        msg = JSON.parse(item.message);
      else
        return ''

      if (msg.extendedData.type == 111)
        messages = messages + "[表情]，";
      else if (msg.extendedData.type == 11)
        messages = messages + "[图片]，";
      else
        messages =
        messages +
        JSON.parse(item.message).message +
        " ";
    }
    return messages;
  } else {
    return "";
  }
}

// 相对路径地址拼接为oss绝对地址
export const getRelativeOss = (url) => {
  if (!url) return
  if (url.startsWith('http://') || url.startsWith('https://'))
    return url
  else
    return 'https://xzcs-video.oss-cn-beijing.aliyuncs.com' + url

};

// 头像地址拼接oss地址
export const getQavatarOss = (url) => {
  if (!url) return
  if (url.startsWith('http://') || url.startsWith('https://'))
    return url
  else
    return 'https://xzcs-video.oss-cn-beijing.aliyuncs.com' + url

};

// 文字高亮 keyword 需要高亮的文字
export const hightLightText = (text, keyword) => {
  if (!text) return
  for (let key of keyword) {
    if (hasSpecialStr(key)) {
      text = text + ''
    } else {
      const reg = new RegExp(key, 'gi') // 动态正则表达式
      text = text.replace(reg, `<em>${key}</em>`) // 使用replace替换
    }
  }
  return text
};

// JS判断字符串是否含有特殊符号，包括英文与中文两种输入模式。
function hasSpecialStr(str) {
  var specialChars = "~·`!！@#$￥%^…&*()（）—-_=+[]{}【】、|\\;:；：'\"“‘,./<>《》?？，。emEM";
  // var len=specialChars.length;
  // for ( var i = 0; i < len; i++){
  //     if (str.indexOf(specialChars.substring(i,i+1)) != -1){
  //         return true;
  //     }
  // }
  if (specialChars.indexOf(str) != -1) return true
  return false;
}

function hasSpecialStr2(str) {
  var specialChars = "~·`!！@#$￥%^…&*()（）—-_=+[]{}【】、|\\;:；：'\"“‘,./<>《》?？，。emEM";
  var len = specialChars.length;
  for (var i = 0; i < len; i++) {
    if (str.indexOf(specialChars.substring(i, i + 1)) != -1) {
      return true;
    }
  }
  return false;
}

export const getText = (str, num = 80) => {
  if (!str) {
    return
  }

  let text = str.replace(/<[^<>]+>/g, "")
  text = text.replace(/&nbsp;/gi, " ");
  text = text.replace(/nbsp;/gi, " ");

  if (text.length > num) return text.substring(0, num) + '...'
  return text
}

export const replaceurl = (detail, name) => {
  let i = 1
  var content = detail.replace(/<img[^>]*>/gi, function (match) {
    var match = match.replace(
      /alt=""/g,
      `alt="${name}-${i++}"`
    )
    return match
  })
  return content
}
export function addHiddenPBeforeATags(html, prependText) {
  // 正则表达式来匹配<a>标签，并捕获其href和文本内容  
  // 注意：这是一个非常简化的版本，它不会处理复杂的属性或嵌套  
  const regex = /<a\s+[^>]*>([^<]*)<\/a>/gi;

  // 替换函数，用于在每个<a>标签前添加<p>标签  
  const replacer = (match, linkText) => {
    // 构造隐藏的<p>标签  
    const hiddenPTag = `<span style="display:none;">${linkText}</span>`;

    // 返回替换后的HTML片段，包括隐藏的<p>标签和原始的<a>标签  
    return hiddenPTag + match;
  };

  // 使用正则表达式和替换函数来处理HTML字符串  
  return html.replace(regex, replacer);
}
export function internally(text) {
  text = addHiddenPBeforeATags(text)
  let keywords = {
    '增值税': 'https://www.xzcs2022.com/quizdata/12960.html',
    '个人所得税': 'https://www.xzcs2022.com/quizdata/15988.html',
    '土地增值税': 'https://www.xzcs2022.com/quizdata/12002.html',
    '印花税': 'https://www.xzcs2022.com/quizdata/16488.html',
    '代扣代缴': 'https://www.xzcs2022.com/quizdata/18756.html',
    '工资薪金': 'https://www.xzcs2022.com/quizdata/21435.html',
    '存货': 'https://www.xzcs2022.com/quizdata/7083.html',
    '固定资产': 'https://www.xzcs2022.com/quizdata/7283.html',
    '无形资产': 'https://www.xzcs2022.com/quizdata/7366.html',
    '政府补助': 'https://www.xzcs2022.com/quizdata/7921.html',
  }

  for (let item in keywords) {
    text = text.replace(new RegExp(item), `<a href="${keywords[item]}" ref="noopener" target="_blank">${item}</a>`);
  }

  return text
}


export const escape2Html = (str) => {
  var arrEntities = {
    'nbsp': ' ',
    'amp': '&',
    'quot': '"'
  };
  return str.replace(/&(nbsp|amp|quot);/ig, function (all, t) {
    return arrEntities[t];
  });
}

export const getTime = (time) => {

  var date = new Date(time);
  let Y = date.getFullYear() + '-';
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
  let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
  let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
  let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  return `${Y}${M}${D}${h}${m}${s}`
}

export const getTime2 = (time) => {

  var date = new Date(time);
  let Y = date.getFullYear() + '-';
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
  return `${Y}${M}${D}`
}

export const getTime3 = (time) => {

  var date = new Date(time);
  let Y = date.getFullYear() + '-';
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
  return `${Y}${M}${D}`
}

export const isCurrentTimeBeforeGivenTime = (givenTimeString) => {
  // 将给定时间字符串拆分为小时和分钟
  const [hours, minutes] = givenTimeString.split(":").map(Number);

  // 获取当前时间的小时和分钟
  const now = new Date();
  const currentHours = now.getHours();
  const currentMinutes = now.getMinutes();

  // 如果当前小时小于给定小时，或者当前小时相等但当前分钟小于给定分钟，则返回 true
  return (
    currentHours < hours ||
    (currentHours === hours && currentMinutes < minutes)
  );
}

export const isToday = (date) => {
  // 获取当前日期的开始时间（00:00:00）和结束时间（23:59:59）
  const todayStart = new Date(new Date().toLocaleDateString()).setHours(
    0,
    0,
    0,
    0
  );
  const todayEnd = new Date(todayStart).setHours(23, 59, 59, 999);

  // 将传入的时间对象转换为时间戳，并与今天的开始时间和结束时间进行比较
  const dateTimestamp = date.getTime();
  return dateTimestamp >= todayStart && dateTimestamp <= todayEnd;
}

export const parseDate = (dateString) => {
  const [year, month, day] = dateString.split('-').map(Number);
  return new Date(year, month - 1, day); // 注意：月份在 Date 构造函数中是 0-11，所以需要减 1
}

export const parseDateTime = (dateTimeString) => {
  const [datePart, timePart] = dateTimeString.split(' ');
  const [year, month, day] = datePart.split('-').map(Number);
  const [hours, minutes, seconds] = timePart.split(':').map(Number);
  return new Date(year, month - 1, day, hours, minutes, seconds);
}


export const IEVersion = () => {
  var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
  var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
  var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
  var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
  if (isIE) {
    var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
    reIE.test(userAgent);
    var fIEVersion = parseFloat(RegExp["$1"]);
    if (fIEVersion == 7) {
      return 7;
    } else if (fIEVersion == 8) {
      return 8;
    } else if (fIEVersion == 9) {
      return 9;
    } else if (fIEVersion == 10) {
      return 10;
    } else {
      return 6; //IE版本<=7
    }
  } else if (isEdge) {
    return 'edge'; //edge
  } else if (isIE11) {
    return 11; //IE11
  } else {
    return -1; //不是ie浏览器
  }
}

export function getDiffDay(date_1, date_2) {
  // 计算两个日期之间的差值
  let totalDays, diffDate
  let myDate_1 = Date.parse(date_1)
  let myDate_2 = date_2
  // 将两个日期都转换为毫秒格式，然后做差
  diffDate = Math.abs(myDate_1 - myDate_2) // 取相差毫秒数的绝对值

  totalDays = Math.floor(diffDate / (1000 * 3600 * 24)) // 向下取整
  // console.log(totalDays)

  return totalDays // 相差的天数
}

export function getServiceType(type) {
  switch (type) {
    case 1:
      return "官方服务商";
    case 2:
      return "金牌服务商";
    case 3:
      return "银牌服务商";
    case 4:
      return "铜牌服务商";
    case 5:
      return "一般服务商";
    default:
      break;
  }
}

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

function splitText(text, keywords) {
  const regexp = new RegExp(
    keywords
    .map((keyword) => escapeRegExp(String(keyword).trim()))
    .join("|"),
    "gi"
  );
  return text.replace(/\t/g, "").replace(regexp, "\t$&\t").split(/\t/);
}

export function wrapText(text, keywords) {
  let str = "";
  // 统计数字
  let num = 0
  splitText(text, keywords).map((substr, i) => {
    // str += i % 2 === 0 ? substr : `<em>${substr}</em>`;
    if (i % 2 === 0) {
      str += substr
    } else {
      num++
      str += `<em>${substr}</em>`
    }
    return true;
  });
  return {
    str: str,
    num: num
  };
}

//去除富文本字符串中的html标签
export function removeHTMLTags(str) {
  var newStr = str.replace(/<\/?[^>]*>/g, ''); //去除HTML tag
  newStr = newStr.replace(/[ | ]*\n/g, '\n'); //去除行尾空白
  newStr = newStr.replace(/\n[\s| | ]*\r/g, '\n'); //去除多余空行
  newStr = newStr.replace(/&nbsp;/ig, ''); //去掉&nbsp;
  return newStr;
}


/*
 *   arr 需要查的数组对象
 *   path 需要查的值
 *   key 需要查的键名
 */
export function getArr_objKey(arr, path, key) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] == path) {
      return i
    }
  }
  return 0;
}




export function answerFormat(resultList, queryKeywords, retrieveFieldsIndex) {
  if (!queryKeywords || queryKeywords.length == 0) queryKeywords = []
  for (let i = 0; i < resultList.length; i++) {
    let answer = resultList[i].quizData.answer_content
    let title = resultList[i].quizData.title
    if (retrieveFieldsIndex == 1)
      queryKeywords.forEach(keyword => {
        if (!hasSpecialStr2(keyword))
          title = title.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
      })
    else
      queryKeywords.forEach(keyword => {
        if (!hasSpecialStr2(keyword)) {
          answer = answer.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
          title = title.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
        }
      })
    resultList[i].quizData.answer_content = answer
    resultList[i].quizData.title = title
  }
  return resultList
}

export function answerFormat2(resultList, queryKeywords, retrieveFields) {
  if (!queryKeywords || queryKeywords.length == 0) queryKeywords = []
  for (let i = 0; i < resultList.length; i++) {
    let answer = resultList[i].policyData.info_content
    let title = resultList[i].policyData.title
    let push_number = resultList[i].policyData.push_number
    let push_date = resultList[i].policyData.push_date


    if (retrieveFields == 'push_number')
      queryKeywords.forEach(keyword => {
        if (!hasSpecialStr2(keyword))
          push_number = push_number.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
      })
    else if (retrieveFields == 'title')
      queryKeywords.forEach(keyword => {
        if (!hasSpecialStr2(keyword))
          title = title.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
      })
    else if (retrieveFields == 'info_content_text')
      queryKeywords.forEach(keyword => {
        if (!hasSpecialStr2(keyword)) {
          answer = answer.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
          title = title.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
        }
      })
    else if (retrieveFields == 'push_date')
      push_date = "<em>" + push_date + '</em>';

    resultList[i].policyData.info_content = answer
    resultList[i].policyData.push_date = push_date
    resultList[i].policyData.title = title
    resultList[i].policyData.push_number = push_number
  }
  return resultList
}

export function answerFormat3(resultList, queryKeywords, retrieveFields) {
  if (!queryKeywords || queryKeywords.length == 0) queryKeywords = []
  for (let i = 0; i < resultList.length; i++) {
    let answer = resultList[i].policyData.info_content
    let name = resultList[i].policyData.name
    let push_number = resultList[i].policyData.push_number
    let push_date = resultList[i].policyData.push_date

    if (retrieveFields == 'push_number')
      queryKeywords.forEach(keyword => {
        if (!hasSpecialStr2(keyword))
          push_number = push_number.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
      })
    else if (retrieveFields == 'name')
      queryKeywords.forEach(keyword => {
        if (!hasSpecialStr2(keyword))
          name = name.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
      })
    else if (retrieveFields == 'info_content_text')
      queryKeywords.forEach(keyword => {
        if (!hasSpecialStr2(keyword)) {
          answer = answer.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
          name = name.replace(new RegExp(keyword, "g"), "<em>" + keyword + '</em>');
        }
      })
    else if (retrieveFields == 'push_date')
      push_date = "<em>" + push_date + '</em>';

    resultList[i].policyData.info_content = answer
    resultList[i].policyData.name = name
    resultList[i].policyData.push_date = push_date
    resultList[i].policyData.push_number = push_number
  }
  return resultList
}

export function readJsonFileContent(jsonfileUrl) {
  return new Promise(function (resolve, reject) {
    let xhr = new XMLHttpRequest();
    xhr.open("get", jsonfileUrl, true);
    xhr.responseType = "blob";
    xhr.onload = function () {
      if (this.status == 200) {
        const reader = new FileReader();
        reader.onload = () => {
          var data = JSON.parse(reader.result)
          resolve({
            data: data
          })
        };
        reader.readAsText(this.response, 'utf-8');
      }
    };
    xhr.send();

  })
}

export function getCateListName(id, cateList) {
  for (let items of cateList) {
    for (let item of items.list) {

      if (item.id == id) return item.name
    }
  }
}


export function wrapLinksWithAnchorTags(text) {
  // 匹配URL的正则表达式，包括http, https, ftp等协议，以及可选的查询参数  
  const urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;

  // 使用正则表达式替换函数来替换所有匹配的URL  
  return text.replace(urlRegex, function (url) {
    // 创建一个a标签并返回  
    return `<a href="/link?url=${encodeURIComponent(url)}" target="_blank">${url}</a>`;
  });
}

export function getEmoji(richText, emojiList2) {
  // 创建一个DOM解析器来解析富文本字符串
  const parser = new DOMParser();
  const doc = parser.parseFromString(richText, "text/html");

  // 定义一个映射对象，将表情文本映射到图片URL
  const emojiToImageMap = emojiList2;

  // 定义一个函数来递归地遍历DOM树并替换文本节点
  function replaceTextNodes(node) {
    if (node.nodeType === Node.TEXT_NODE) {
      const fragment = document.createDocumentFragment();
      const parts = node.textContent.split(/(\[[^\]]+\])/g); // 使用正则表达式分割文本和表情

      parts.forEach((part) => {
        if (emojiToImageMap.hasOwnProperty(part.trim())) {
          // 如果是表情文本，则创建一个图片节点并添加到文档片段中
          const img = document.createElement("img");
          img.src = emojiToImageMap[part.trim()];
          img.alt = part.trim().slice(1, -1); // 设置alt属性为表情文本的内容（去掉方括号）
          fragment.appendChild(img);
        } else {
          // 如果不是表情文本，则创建一个文本节点并添加到文档片段中
          fragment.appendChild(document.createTextNode(part));
        }
      });

      // 替换原始的文本节点为新的文档片段
      node.parentNode.replaceChild(fragment, node);
    } else {
      // 如果是元素节点，则递归地遍历其子节点
      node = node.firstChild;
      while (node) {
        const nextNode = node.nextSibling;
        replaceTextNodes(node);
        node = nextNode;
      }
    }
  }

  // 开始替换过程，从文档的body节点开始
  replaceTextNodes(doc.body);

  // 将修改后的DOM序列化为字符串并返回
  return doc.body.innerHTML;
}

export function extractTitleData(text) {
  const result = {
    title: '',
    id: '',
    documentType: ''
  };

  // 提取纯文本部分（直到第一个标签或字符串结尾）
  const titleMatch = text.match(/^(.*?)(?:<|$)/s);
  if (titleMatch) {
    result.title = titleMatch[1].trim();
  }

  // 提取id（如果有）
  const idMatch = text.match(/<id>(\d+)<\/id>/);
  if (idMatch) {
    result.id = idMatch[1];
  }

  // 提取documentType（如果有）
  const docTypeMatch = text.match(/<documentType>(\w+)<\/documentType>/);
  if (docTypeMatch) {
    result.documentType = docTypeMatch[1];
  }

  return result;
}
